package com.example.imgup;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.view.GestureDetector;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private List<String> imagePaths;
    private int currentImageIndex = 0;
    private Picasso picasso;
    private GestureDetector gestureDetector;
    private ZoomImageView zoomImageView;

    @SuppressLint("WrongViewCast")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        zoomImageView = findViewById(R.id.zoomImageView);
        Button previousButton = findViewById(R.id.previousButton);
        Button nextButton = findViewById(R.id.nextButton);
        Button importButton = findViewById(R.id.importButton);
        Button annotateButton = findViewById(R.id.button4);
        Button saveButton = findViewById(R.id.button5);
        Button undoButton = findViewById(R.id.button6);
        importButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 打开图库并选择文件夹
                openGallery();
            }
        });

        previousButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 显示上一张图片
                showPreviousImage();
            }
        });

        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 显示下一张图片
                showNextImage();
            }
        });

        // 设置单击监听
        zoomImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理单击事件
            }
        });
        annotateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理标注框列表
                Intent intent = new Intent(getApplicationContext(), MainActivity2.class);

                // 启动 MainActivity2
                startActivity(intent);
            }
        });
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSaveFormatMenu(v);
            }
        });
        undoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                zoomImageView.undoLastAnnotation();
            }
        });

        zoomImageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return zoomImageView.onTouchEvent(event);
            }
        });
    }


    private static final int REQUEST_CODE_OPEN_DOCUMENT_TREE = 1;

    private void openGallery() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
        startActivityForResult(intent, REQUEST_CODE_OPEN_DOCUMENT_TREE);
    }
//导入图库
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_OPEN_DOCUMENT_TREE && resultCode == RESULT_OK) {
            Uri treeUri = data.getData();
            if (treeUri != null) {
                // 通过文件夹URI获取图片路径列表或URI列表
                imagePaths = getImagePathsFromFolder(treeUri);
                // 显示第一张图片
                showImage(zoomImageView, 0);
                // 只对第一张图片执行保存操作
                if (imagePaths != null && !imagePaths.isEmpty() && currentImageIndex == 0) {
                    // 添加对 imagePaths.get(0) 是否为空的检查
                    if (imagePaths.get(0) != null) {
                        // 传递图片路径作为参数
                        saveAnnotationsAsYOLOFormat(imagePaths.get(0));
                    } else {
                        Log.e("Error", "Image path at index 0 is null.");
                    }
                }
            }
        }
    }
    private List<String> getImagePathsFromFolder(Uri folderUri) {
        List<String> imagePaths = new ArrayList<>();

        ContentResolver contentResolver = getContentResolver();
        Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(folderUri,
                DocumentsContract.getTreeDocumentId(folderUri));

        Cursor cursor = contentResolver.query(childrenUri,
                new String[]{DocumentsContract.Document.COLUMN_DOCUMENT_ID, DocumentsContract.Document.COLUMN_MIME_TYPE},
                null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            do {
                String documentId = cursor.getString(0);
                String mimeType = cursor.getString(1);

                if (mimeType != null && mimeType.startsWith("image/")) {
                    Uri imageUri = DocumentsContract.buildDocumentUriUsingTree(folderUri, documentId);
                    imagePaths.add(imageUri.toString());
                }
            } while (cursor.moveToNext());

            cursor.close();
        }

        return imagePaths;
    }
    private void showImage(ImageView imageView, int position) {
        if (imagePaths != null && position >= 0 && position < imagePaths.size()) {
            String imagePath = imagePaths.get(position);
            Picasso.get().load(imagePath).into(imageView);
        }
    }

    private void showPreviousImage() {
        // 清除之前的标注框和标签
        zoomImageView.clearAnnotations();
        if (currentImageIndex > 0) {
            currentImageIndex--;
            Log.d("SaveDebug", "Saving annotations before switching image: " +
                    imagePaths.get(currentImageIndex));
            showImage(zoomImageView, currentImageIndex);
            // 在这里等待标注框的绘制完成
            zoomImageView.setOnAnnotationsDrawnListener(() -> {
                saveAnnotationsAsYOLOFormat(imagePaths.get(currentImageIndex));
                // 保存完成后移除监听器，避免重复保存
                zoomImageView.setOnAnnotationsDrawnListener(null);
            });
        }
    }

    private void showNextImage() {
        // 清除之前的标注框和标签
        zoomImageView.clearAnnotations();
        if (currentImageIndex < imagePaths.size() - 1) {
            currentImageIndex++;
            Log.d("SaveDebug", "Saving annotations before switching image: " +
                    imagePaths.get(currentImageIndex));
            showImage(zoomImageView, currentImageIndex);
            // 在这里等待标注框的绘制完成
            zoomImageView.setOnAnnotationsDrawnListener(() -> {
                saveAnnotationsAsYOLOFormat(imagePaths.get(currentImageIndex));
                // 保存完成后移除监听器，避免重复保存
                zoomImageView.setOnAnnotationsDrawnListener(null);
            });
        }
    }
    private static final int REQUEST_CODE_SAVE_PATH = 2;
    @SuppressLint("ResourceType")
    private void showSaveFormatMenu(View anchorView) {
        PopupMenu popupMenu = new PopupMenu(MainActivity.this, anchorView);
        popupMenu.getMenuInflater().inflate(R.xml.save_format_menu, popupMenu.getMenu());
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.menu_voc_format) {
                    saveAnnotationsAsVOCFormat();
                } else if (item.getItemId() == R.id.menu_yolo_format) {
                    if (imagePaths != null && !imagePaths.isEmpty() && currentImageIndex == 0) {
                        if (imagePaths.get(0) != null) {
                            saveAnnotationsAsYOLOFormat(imagePaths.get(0));
                        } else {
                            Log.e("Error", "Image path at index 0 is null.");
                        }
                    }
                } else if (item.getItemId() == R.id.menu_createml_format) {
                    saveAnnotationsAsCreateMLFormat();
                }
                return true;
            }
        });
        popupMenu.show();
    }
    private void saveAnnotationsAsVOCFormat() {

    }
    private void saveAnnotationsAsYOLOFormat(String imagePath) {
        if (imagePath != null && !zoomImageView.getAnnotations().isEmpty()) {
            //File savePath = new File(Environment.getExternalStorageDirectory(), "photo2");
            File savePath = new File(getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "photo2");
            if (!savePath.exists()) {
                savePath.mkdirs();
            }

            String imageName = getImageNameFromPath(imagePath);
            String txtFileName = imageName.replace(".jpg", ".txt");
            String txtFilePath = new File(savePath, txtFileName).getPath() + ".txt"; // 添加文件扩展

            ArrayList<ArrayList<Object>> rectangleData = zoomImageView.getRectangleData();
            Log.d("Debug", "Rectangle Data before saving: " + rectangleData.toString());
            try {
                saveRectangleDataToTxt(rectangleData, txtFilePath);
                Log.d("SaveDebug", "Successfully saved data to file: " + txtFilePath);
            } catch (Exception e) {
                Log.e("SaveDebug", "Error saving data to file: " + txtFilePath, e);
            }
        }
    }
    private String getImageNameFromPath(String imagePath) {
        String[] pathSegments = imagePath.split("/");
        return pathSegments[pathSegments.length - 1];
    }

    private void saveRectangleDataToTxt(ArrayList<ArrayList<Object>> rectangleData, String txtFilePath) {
        Log.d("SaveDebug", "Saving data to file: " + txtFilePath);
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(txtFilePath));

            for (ArrayList<Object> rectangleInfo : rectangleData) {
                String label = (String) rectangleInfo.get(0);
                float centerX = (float) rectangleInfo.get(1);
                float centerY = (float) rectangleInfo.get(2);
                float relativeWidth = (float) rectangleInfo.get(3);
                float relativeHeight = (float) rectangleInfo.get(4);

                // 将矩形框信息按照 YOLO 格式写入 txt 文件
                String line = String.format("%s %.6f %.6f %.6f %.6f", label, centerX, centerY, relativeWidth, relativeHeight);
                writer.write(line);
                writer.newLine();
            }

            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void saveAnnotationsAsCreateMLFormat() {
        // 实现保存为CreateML格式的逻辑，生成JSON文件
    }
}